﻿Imports System.Data.SqlClient

Public Class DivisiDb
    Dim connectionString As String

    Public Sub New(ByVal connectionString As String)
        Me.connectionString = connectionString
    End Sub

    Public Function isExist(ByVal kodeDivisi As String) As Boolean
        Dim total As Integer
        Dim connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand("select count(*) from TB_MST_DIVISI where kode_divisi = @kodeDivisi", connection)

        Try
            connection.Open()
            command.Parameters.AddWithValue("@kodeDivisi", kodeDivisi)
            total = CInt(command.ExecuteScalar())
        Catch ex As SqlException
            Throw ex
        Finally
            connection.Close()
        End Try

        If total > 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Sub insert(ByVal kodeSatker As String, ByVal kodeDivisi As String, ByVal deskripsi As String, ByVal isActive As String)
        Dim connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand("insert into TB_MST_DIVISI (id_satker,kode_divisi,deskripsi,is_active,tgl_update) values ((select id_satker from TB_MST_SATKER where kode_satker = @kodeSatker), @kodeDivisi, @deskripsi, @isActive, CURRENT_TIMESTAMP)", connection)
        Try
            connection.Open()
            command.Parameters.AddWithValue("@kodeSatker", kodeSatker)
            command.Parameters.AddWithValue("@kodeDivisi", kodeDivisi)
            command.Parameters.AddWithValue("@deskripsi", deskripsi)
            command.Parameters.AddWithValue("@isActive", isActive)
            command.ExecuteNonQuery()
        Catch ex As SqlException
            Throw ex
        Finally
            connection.Close()
        End Try
    End Sub

    Public Sub update(ByVal idDivisi As String, ByVal kodeSatker As String, ByVal kodeDivisi As String, ByVal deskripsi As String, ByVal isActive As String)
        Dim connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand("update TB_MST_DIVISI set id_satker=(select id_satker from TB_MST_SATKER where kode_satker = @kodeSatker), kode_divisi=@kodeDivisi, deskripsi=@deskripsi, is_active=@isActive, tgl_update=current_timestamp where id_divisi = @idDivisi", connection)
        Try
            connection.Open()
            command.Parameters.AddWithValue("@kodeSatker", kodeSatker)
            command.Parameters.AddWithValue("@kodeDivisi", kodeDivisi)
            command.Parameters.AddWithValue("@deskripsi", deskripsi)
            command.Parameters.AddWithValue("@isActive", isActive)
            command.Parameters.AddWithValue("@idDivisi", idDivisi)
            command.ExecuteNonQuery()
        Catch ex As SqlException
            Throw ex
        Finally
            connection.Close()
        End Try
    End Sub

End Class
